﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web;
using Word = Microsoft.Office.Interop.Word;


namespace Siva.CBC.Barnacle.ashx
{
    /// <summary>
    /// xingyeHandler 的摘要说明
    /// </summary>
    public class xingyeHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //1.接收参数
            string ht = context.Request.Form["ht"];
            string aa = context.Request.Form["aa"];
            string bb = context.Request.Form["bb"];
            string cc = context.Request.Form["cc"];
            string dd = context.Request.Form["dd"];
            string ee = context.Request.Form["ee"];
            string ff = context.Request.Form["ff"];
            string gg = context.Request.Form["gg"];
            string hh = context.Request.Form["hh"];
            string ii = context.Request.Form["ii"];
            string jj = context.Request.Form["jj"];
            string kk = context.Request.Form["kk"];
            string ll = context.Request.Form["ll"];
            string mm = context.Request.Form["mm"];
            string nn = context.Request.Form["nn"];

            if (string.IsNullOrEmpty(ht) || string.IsNullOrEmpty(aa) || string.IsNullOrEmpty(bb) || string.IsNullOrEmpty(cc) || string.IsNullOrEmpty(dd) || string.IsNullOrEmpty(ee) || string.IsNullOrEmpty(ff) || string.IsNullOrEmpty(gg) || string.IsNullOrEmpty(hh) || string.IsNullOrEmpty(ii) || string.IsNullOrEmpty(jj) || string.IsNullOrEmpty(kk) || string.IsNullOrEmpty(ll) || string.IsNullOrEmpty(mm) || string.IsNullOrEmpty(nn))
            {
                context.Response.Write("参数错误，请刷新页面重来！");
                return;
            }
            //模板所在位置
            string TemplatePath = context.Server.MapPath("/") + "App_LocalResources\\XingYe\\" + ht + ".docx";
            //保存的路径
            string path = context.Server.MapPath("/") + "Xingye\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
            //判断目录是否存在
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string savePath = path + nn + ".docx";
            //如果文件存在
            while (File.Exists(savePath))
            {
                savePath = savePath.Remove(savePath.Length - 4) + "(1)" + ".docx";
            }


            //使用自带的WORD进行替换
            if (!File.Exists(TemplatePath))
            {
                context.Response.Write("模板文件不存在，请联系管理员");
                return;
            }
            Word.Application wordApp = new Word.Application();
            wordApp.Visible = false;
            wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
            Word.Document doc = wordApp.Documents.Open(TemplatePath);
            object replace = Word.WdReplace.wdReplaceOne;
            try
            {
                doc.Content.Find.Execute(FindText: "$aa", ReplaceWith: aa, Replace: replace);
                doc.Content.Find.Execute(FindText: "$bb", ReplaceWith: bb, Replace: replace);
                doc.Content.Find.Execute(FindText: "$cc", ReplaceWith: cc, Replace: replace);
                doc.Content.Find.Execute(FindText: "$dd", ReplaceWith: dd, Replace: replace);
                doc.Content.Find.Execute(FindText: "$ee", ReplaceWith: ee, Replace: replace);
                doc.Content.Find.Execute(FindText: "$ff", ReplaceWith: ff, Replace: replace);
                doc.Content.Find.Execute(FindText: "$gg", ReplaceWith: gg, Replace: replace);
                doc.Content.Find.Execute(FindText: "$hh", ReplaceWith: hh, Replace: replace);
                doc.Content.Find.Execute(FindText: "$ii", ReplaceWith: ii, Replace: replace);
                doc.Content.Find.Execute(FindText: "$jj", ReplaceWith: jj, Replace: replace);
                doc.Content.Find.Execute(FindText: "$kk", ReplaceWith: kk, Replace: replace);
                doc.Content.Find.Execute(FindText: "$ll", ReplaceWith: ll, Replace: replace);
                doc.SaveAs(savePath);
            }
            catch (Exception err)
            {

                context.Response.Write("Error: " + err.Message);
                return;
            }
            finally
            {
                doc.Close();
                wordApp.Quit();
            }


            //准备发邮件
            string to = ConfigurationManager.AppSettings[mm];
            if (string.IsNullOrEmpty(to))
            {
                context.Response.Write("邮件接收人不存在，请联系管理员");
                return;
            }
            SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

            string from = smtpSection.From;
            //string to = emails[mm];
            string pwd = smtpSection.Network.Password;
            string smtp = smtpSection.Network.Host;

            MailMessage msg = new MailMessage();
            msg.To.Add(to);
            msg.From = new MailAddress(from);
            msg.Subject = "分期还款申请书--" + nn;
            msg.Attachments.Add(new Attachment(savePath));


            SmtpClient client = new SmtpClient(smtp);
            client.Credentials = new System.Net.NetworkCredential(from, pwd);

            try
            {
                client.Send(msg);
                context.Response.Write("已成功发送给" + mm);
            }
            catch (Exception err)
            {

                context.Response.Write(err.Message);
            }
            finally
            {
                msg.Dispose();
                client.Dispose();
            }


            //此次操作写入日志
            //string sql = string.Format("insert into xingyelogs(email,filename) values('{0}','{1}')",to,savePath);
            string sql = "insert into xingyelogs(email,filename,IP) values(?emailValue,?filenameValue,?IPValue)";
            MySql.Data.MySqlClient.MySqlParameter[] para = new MySql.Data.MySqlClient.MySqlParameter[]
            {
                new MySql.Data.MySqlClient.MySqlParameter("?emailValue",MySql.Data.MySqlClient.MySqlDbType.VarString){ Value=to},
                new MySql.Data.MySqlClient.MySqlParameter("?filenameValue",MySql.Data.MySqlClient.MySqlDbType.VarString){Value=savePath},
                new MySql.Data.MySqlClient.MySqlParameter("?IPValue",MySql.Data.MySqlClient.MySqlDbType.VarString){Value=context.Request.ServerVariables["REMOTE_ADDR"]}
            };
            int result = SqlHelper.ExecuteNonQuery(sql, para);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}